<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" type="circle" :percentage="percentage" class="progress" />
    </el-upload>
  </div>

</template>

<script>
// 引入必要的COS模块
const COS = require('cos-js-sdk-v5')
// 实例化对象
const cos = new COS({
  SecretId: 'AKIDNagW6PRDihQu74lCNHwKSKvFJ6crqYz9', // 身份识别ID
  SecretKey: 'uZx5wXrugCRQ8ZlgKhncAQQ9bmhLj7E5' // 身份秘钥
})
export default {
  name: 'Updateimg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      percentage: 0,
      showProgress: false
    }
  },
  methods: {

    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
    },
    upload(file) {
      this.showProgress = true
      cos.putObject({
        Bucket: 'xiaosansui-1311503682', /* 存储桶 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: file.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: file.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
          // if(this.percentage){

          // }
        }
      }, (err, data) => {
        console.log(err || data)
        // 上传成功之后
        this.imageUrl = `https://${data.Location}`
        this.$emit('input', this.imageUrl)
        this.showProgress = false
      })
    }

  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress{
   position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
</style>
